/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bm.main.threading;

import com.bm.setting.ServerConfig;
import com.bm.util.MessagePrinter;
import com.bm.util.Util;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author ssm
 */
public class RequestOutbox implements Runnable {

    private int maksimum_data_per_request;
    private String url;

    public RequestOutbox(int maksimum_data_per_request, String url) {
        this.maksimum_data_per_request = maksimum_data_per_request;
        this.url = url;
    }

    @Override
    public void run() {
        while (true) {
            int waiting_interval = 15;
            String data = Util.doRequestWithTimeout("", url + "/request_outbox/" + this.maksimum_data_per_request, false, 30000, 1);
            if (data.trim().equalsIgnoreCase("none")) {
                MessagePrinter.print("Tidak ada transaksi");
            } else {
                Connection conn = ServerConfig.getConnection();
                JsonArray jsaResp = new JsonArray();

                JsonParser jse = new JsonParser();

                JsonArray jsa = null;
                try {
                    jsa = jse.parse(data).getAsJsonArray();
                } catch (Exception e) {
                    System.out.println("Error Parsing web " + e.getMessage());
                    try {
                        Thread.sleep(15 * 1000);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(RequestOutbox.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    ServerConfig.close(conn);
                    continue;
                }

                for (int i = 0; i < jsa.size(); i++) {
                    waiting_interval--;
                    JsonObject jso = jsa.get(i).getAsJsonObject();
                    MessagePrinter.print("Memproses " + (i + 1) + " dari " + jsa.size() + " data outbox (id_message : " + jso.get("id_message").getAsString() + ")");

                    String receiver = jso.get("receiver").getAsString();
                    String isi_sms = jso.get("content").getAsString();
                    String id_modul = jso.get("id_modul").getAsString();
                    PreparedStatement pst = null;
                    try {
                        String query = "INSERT INTO kamisa.message_outbox"
                                + " (id_transaksi,"
                                + " receiver,"
                                + " content,"
                                + " id_modul,"
                                + " is_sent,"
                                + " date_created,"
                                + " id_member,"
                                + " id_request"
                                + ")"
                                + " values (?,?,?,?,0,now(),?,?)";
                        pst = conn.prepareStatement(query);
                        pst.setLong(1, jso.get("id_message").getAsLong());
                        pst.setString(2, receiver);
                        pst.setString(3, isi_sms);
                        pst.setString(4, id_modul);
                        pst.setLong(5, jso.get("id_member").getAsLong());
                        pst.setLong(6, jso.get("id_message").getAsLong());
                        pst.executeUpdate();

                        JsonObject jsoResp = new JsonObject();
                        jsoResp.add("id_message", jso.get("id_message"));
                        jsoResp.add("status", jse.parse("1"));

                        jsaResp.add(jsoResp);
                    } catch (SQLException ex) {
                        System.out.println(ex.getMessage());
                    } finally {
                        ServerConfig.close(pst);
                    }
                }

                ServerConfig.close(conn);
                Util.doRequestWithTimeout(jsaResp.toString(), url + "/update_status_outbox", true, 30000, 1);
            }
            try {
                if (waiting_interval <= 0) {
                    MessagePrinter.print("Menunggu proses outbox berikutnya selama " + waiting_interval + " detik");
                    Thread.sleep(2 * 1000);
                    continue;
                }
                MessagePrinter.print("Menunggu proses outbox berikutnya selama " + waiting_interval + " detik");
                Thread.sleep(waiting_interval * 1000);
            } catch (InterruptedException ex) {
                MessagePrinter.printDebug(ex.getMessage());
            }
        }
    }
}
